package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Order;
import domain.OrderItem;
import domain.Product;
import domain.User;
import service.OrderService;
import service.ProductService;
import service.UserService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class OrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        第一步：提取请求中的用户信息
        JSONObject object=null;
        Response build=null;
        try {
            object = GetRequestJsonUtils.getRequestJsonObject(req);
            JSONArray cart=object.getJSONArray("cart");
            JSONObject info=object.getJSONObject("info");
            ProductService service=new ProductService();
            double totalPrice=0;
            HttpSession session=req.getSession();
            User user=(User) session.getAttribute("user");
            for (int i=0;i<cart.size();i++){
                JSONObject goods=(JSONObject)cart.get(i);
                String id=goods.getString("id");
                double lineTotal=goods.getDoubleValue("lineTotal");
                totalPrice+=lineTotal;
                Product book=service.findProductById(id);
                if(book.getPnum()<goods.getIntValue("number")){
                    build=Response.build(ResponseCode.ERROR,book.getName()+"商品订购数量超出库存！当前库存为："+book.getPnum());
                    resp.setContentType("application/json;charset=utf-8");
                    resp.getWriter().write(JSON.toJSON(build).toString());
                    return;
                }
            }
            OrderService orderService=new OrderService();
            Order order=new Order();
            order.setId(UUID.randomUUID().toString());
            order.setMoney(totalPrice);
            order.setReceiverAddress(info.getString("address"));
            order.setReceiverName(info.getString("name"));
            order.setReceiverPhone(info.getString("phone"));
            order.setPaystate(0);
            order.setUser(user);
            List<OrderItem> orderItemList=new ArrayList<OrderItem>();
            for (int i=0;i<cart.size();i++){//这个循环是插入订单项
                JSONObject goods=(JSONObject)cart.get(i);
                String id=goods.getString("id");
                Product book=service.findProductById(id);
                int number=goods.getIntValue("number");
                OrderItem orderItem=new OrderItem();
                orderItem.setOrder(order);
                orderItem.setBuynum(number);
                orderItem.setP(book);
                orderItemList.add(orderItem);
            }
            order.setOrderItems(orderItemList);
            orderService.commitOrder(order);
            build=Response.build(ResponseCode.SUCCESS);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
        }catch (Exception e){//请求参数格式错误或者数据库异常返回消息
            build=Response.build(ResponseCode.ERROR_PARAM);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }
    }
}
